package com.bfsuolframework.core.configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.bfsuolframework.core.spring.SpringBeanLoader;

public class DbConfigLoader implements ConfigLoader {

	private ConfigLoaderService configService = (ConfigLoaderService)SpringBeanLoader.getBean("configLoaderService");

	public DbConfigLoader(){}
	public DbConfigLoader(ConfigLoaderService configService){
		this.configService = configService;
	}

	public Properties load() throws Exception{
		ConfigLoaderService configService = (ConfigLoaderService)SpringBeanLoader.getBean("configLoaderService");
		if(configService == null){
			throw new Exception("Config Loader Service not Find!");
		}
		Properties properties = new Properties();
		properties.putAll(configService.getAllConfig());
		return properties;
		
	}

	public void save(Properties properties) throws Exception {
		if(configService == null){
			throw new Exception("Config Loader Service not Find!");
		}
		try {
			Map<String,String> config = new HashMap<String,String>();
			for(String key : properties.stringPropertyNames()){
				config.put(key, properties.getProperty(key, ""));
			}
			configService.saveAllConfig(config);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("Can't Save Properties to Database");
		}
	}
}
